﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using VitCode.Web.UI;

namespace VitCode.BaseDataPageCreator.Setting
{
    public class AMSPage : Page
    {
        private StringBuilder content = new StringBuilder();
        private FieldInfo tw_field;
        private TextWriter tw_new;
        private TextWriter tw_old;
        private LanguageHelper m_LangHelper = new LanguageHelper();
         
        public bool IsSetLanguage
        {
            get
            {
                object sessionVal = HttpContext.Current.Session["IsSetLanguage"];
                if (sessionVal != null && sessionVal is bool)
                    return ((bool) sessionVal);
                return true;
            }
            set
            {
                HttpContext.Current.Session["IsSetLanguage"] = value;
            }
        }

        public  void SetPaListlangInfo(PaginationGrid pgList)
        {
            //foreach(IPaginationGridColumn col in pgList.Columns)
            //{
            //    string colName = col.ColumnHeaderText;
            //    m_LangHelper.SetLanguageInfoForString(ref colName);
            //    col.ColumnHeaderText = colName;
            //}
            //IsSetLanguage = false;
        }

        public NameValueCollection LangInfo
        {
            get
            {
                return m_LangHelper.GetFileInfosFromLanguageSettingXml(LanguageHelper.LanguageKey);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if(LanguageHelper.IsOpenLangSetting && IsSetLanguage)
            {
                HttpContext context = HttpContext.Current;
                tw_old = context.Response.Output; //Response不能同时为空OutPut
                tw_new = new StringWriter(content); //枚举协助类，用于获取和缓存带有StringWriter,用来获取页面内容
                Type type_rp = context.Response.GetType();
                //通过反射获取对象的私有字段
                tw_field = type_rp.GetField("_writer", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                tw_field.SetValue(context.Response, tw_new);
            }
        }


        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            if(LanguageHelper.IsOpenLangSetting && IsSetLanguage)
            {
                //替换回Response的OutPut
                tw_field.SetValue(HttpContext.Current.Response, tw_old);
                //做自己的处理
                string strInfo = content.ToString();
                m_LangHelper.SetLanguageInfoForString(ref strInfo);
                HttpContext.Current.Response.Write(strInfo);
            }
        }

    }
}
